import {Injectable} from '@angular/core';
import {Location} from '@angular/common';
import {
    Http,
    Request,
    RequestOptionsArgs,
    RequestMethod,
    Response,
    Headers,
    RequestOptions,
    URLSearchParams
} from '@angular/http';
import {Observable} from 'rxjs/Rx';
import {objectToURLSearchParams} from "@core/object_to_url_search_params";

@Injectable()
export class HttpService {
    baseURL = '/api';
    private jsonHeaders = new Headers({'Content-Type': 'application/json'});

    constructor(private http: Http,
                private location: Location,) {
    }

    // 解析响应数据
    private extractData(res: Response) {
        const body = res.json();
        return body || {};
    }

    // 处理响应错误
    private handleError(error: Response | any) {
        let errMsg: string;
        let errCode: number;
        if (error instanceof Response) {
            let err: string;
            try {
                const body = error.json();
                err = body.message;
                errCode = body.code;
            } catch (e) {
                err = '';
            }
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }

        // console.log(`sessionID:${this.auth.sessionID}`);

        console.error(`http error - ${errCode} - ${errMsg}`);
        // this._loadingSvc.setValue(false);

        // if (errCode === 9999) {
        //     this.auth.logout();
        // }

        return Promise.reject(errMsg);
    }

    // 获取请求的url
    private getRequestURL(url: string): string {
        if (url.charAt(0) !== '/') {
            return `${this.baseURL}/${url}`;
        }
        return `${this.baseURL}${url}`;
    }

    // post请求
    postJSON<T>(url: string, body: any): Promise<T> {
        console.log('body' + JSON.stringify(body));
        const options = new RequestOptions({
            method: RequestMethod.Post,
            body: JSON.stringify(body),
            headers: this.jsonHeaders
        });

        return this.request<T>(this.getRequestURL(url), options);
    }
    // PUT请求
    /**
     * GET
     * @param url
     * @param body
     */
    putJSON<T>(url: string, body: any): Promise<T> {
        console.log('body' + JSON.stringify(body));
        const options = new RequestOptions({
            method: RequestMethod.Put,
            body: JSON.stringify(body),
            headers: this.jsonHeaders
        });

        return this.request<T>(this.getRequestURL(url), options);
    }

    // get请求
    /**
     * GET
     * @param url
     * @param query
     */
    get<T>(url: string, search: any = {}): Promise<T> {

        let query = objectToURLSearchParams(search);

        const options = new RequestOptions({
            method: RequestMethod.Get,
            search: query
        });
        return this.request<T>(this.getRequestURL(url), options);
    }

    // 请求处理
    request<T>(url: string, options?: RequestOptionsArgs): Promise<T> {
        console.log('options' + JSON.stringify(options));
        // if (this.auth.isLoggedIn) {
        //     if (!options) {
        //         options = new RequestOptions();
        //     }

        //     if (!options.headers) {
        //         options.headers = new Headers();
        //     }

        //     options.headers.set('Authorization', `Bearer ${this.auth.sessionID}`);
        // }

        return this.http.request(url, options)
            .toPromise()
            .then(this.extractData)
            .catch((error: Response | any) => {
                let errMsg: string;
                let errCode: number;
                if (error instanceof Response) {
                    let err: string;
                    try {
                        const body = error.json();
                        err = body.message;
                        errCode = body.code;
                    } catch (e) {
                        err = '';
                    }
                    errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
                } else {
                    errMsg = error.message ? error.message : error.toString();
                }

                // this._loadingSvc.setValue(false); // 隐藏等待动画
                alert(errMsg);

                if (errCode === 9999) {
                    // this.auth.logout();
                }

                return Promise.reject(errMsg);
            });
    }

    // tslint:disable-next-line:eofline
}